//
//  WHYComposeViewController.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/12/1.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SVProgressHUD

private let WHYComposeMaxLength = 10

class WHYComposeViewController: UIViewController {

    override func loadView() {
        view = UIView()
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardChanged:",
            name: UIKeyboardWillChangeFrameNotification,
            object: nil)

    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerController.view.bounds.height == 0 {
            textView.becomeFirstResponder()
        }
    }

// MARK: - 监听事件
    @objc private func selectPicturePicker() {
        
        textView.resignFirstResponder()
        
//        当照片选择器显示时，直接返回
        if picturePickerController.view.bounds.height > 0 {
            return
        }
        
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.right.equalTo(view)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        UIView.animateWithDuration(0.8) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc private func keyboardChanged (notification: NSNotification) {
//        QL2(notification)
        
        let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset = -view.bounds.height + rect.origin.y
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        let curve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func selectEmoticon () {
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        textView.becomeFirstResponder()
    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatus () {
        let status = textView.emoticonText
        
        if status.characters.count > WHYComposeMaxLength {
            SVProgressHUD.showErrorWithStatus("输入的内容太长！", maskType: .Gradient)
            return
        }
        
        SVProgressHUD.show()
        let image = picturePickerController.pictures.last
        WHYNetWorkTools.sharedTools.sendStatus(status,
            image: image)
            { (result, error) -> () in
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力", maskType: .Gradient)
                return
            }
            
            SVProgressHUD.dismiss()
            
            NSNotificationCenter.defaultCenter().postNotificationName(WHYWBSendStatusNotification, object: nil)
                
//            QL2(result)
            self.close()
        }
    }
    
// MARK: - 懒加载子控件
    private lazy var picturePickerController = WHYPicturePickerViewController()
    
    private lazy var lengthTipLabel: UILabel = UILabel(title: "还可以输入\(WHYComposeMaxLength)个字符", fontSize: 12)
    
    private lazy var emoticonView: WHYEmoticonView = WHYEmoticonView { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事......",
        titleColor: UIColor.lightGrayColor(),
        fontSize: 18)
    
    private lazy var textView: UITextView = {
        let v = UITextView()
        
        v.textColor = UIColor.darkGrayColor()
        v.font = UIFont.systemFontOfSize(18)
//        垂直方向一直可以滚动
        v.alwaysBounceVertical = true
        
//        当拖动textView时，关闭键盘
//        当键盘关闭时，会输出一个警告
//        [UIWindow endDisablingInterfaceAutorotationAnimated:] called on <UITextEffectsWindow: 0x7fde0591e6f0; frame = (0 0; 375 667); opaque = NO; autoresize = W+H; layer = <UIWindowLayer: 0x7fde036253d0>> without matching -beginDisablingInterfaceAutorotation. Ignoring.
//        v.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        v.delegate = self
        
        return v
    }()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
}

// MARK: - 设置UI
private extension WHYComposeViewController {
    
    func setupUI () {
        
        view.backgroundColor = UIColor.whiteColor()
        automaticallyAdjustsScrollViewInsets = false
        
        prepareNavigation()
        prepareToolBar()
        prepareTextView()
        prepareLengthTipLabel()
        preparePicturePickerController()
        
    }
    
    func preparePicturePickerController () {
        
        picturePickerController.collectionView!.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        addChildViewController(picturePickerController)
        
        view.insertSubview(picturePickerController.view, belowSubview: toolBar)
        
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        }
        
    }
    
    func prepareLengthTipLabel () {
        
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.right.bottom.equalTo(textView).offset(-8)
        }
        
    }
    
    func prepareNavigation () {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",
            style: .Plain,
            target: self,
            action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送",
            style: .Plain,
            target: self,
            action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        let titleLabel = UILabel(title: "发微博",
            titleColor: UIColor.darkGrayColor(),
            fontSize: 15)
        let nameLabel = UILabel(title: WHYUserAccountViewModel.sharedUserAccount.userAccount?.screen_name ?? "",
            titleColor: UIColor.lightGrayColor(),
            fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView)
            make.top.equalTo(titleView)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView)
            make.bottom.equalTo(titleView)
        }
        
        navigationItem.titleView = titleView
        
    }
    
    func prepareToolBar () {
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(44)
        }
        
        let itemSettings = [ ["imageName": "compose_toolbar_picture", "actionName": "selectPicturePicker"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background",
             "actionName": "selectEmoticon" ],
            ["imageName": "compose_addbutton_background"] ]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    func prepareTextView () {
        
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
        
    }
    
}

// MARK: - UITextViewDelegate
extension WHYComposeViewController: UITextViewDelegate {
    
//    是否显示占位文字和发送按钮
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
        
        let length = WHYComposeMaxLength - textView.emoticonText.characters.count
        
        if length >= 0 {
            lengthTipLabel.text = "还可以输入\(length)个字符"
            lengthTipLabel.textColor = UIColor.darkGrayColor()
        }else {
            lengthTipLabel.text = "超出\(-length)个字符"
            lengthTipLabel.textColor = UIColor.redColor()
        }
    }
    
//    当textView开始滚动时，收回键盘
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
}



